<?php

namespace App\Lib\Snowflake;

class SnowflakeGenerator {
    public static $snowflakeInstance;
    public static $redisResolverInstance;
    public static $machineInfo;
    public static function generateId($table){

        if (self::$machineInfo == null) {
            self::$machineInfo = self::getMachineInfo();
        }
        if (self::$snowflakeInstance == null) {
            //TODO 从机器上获取数据中心id和机器id
            self::$snowflakeInstance = new Snowflake(self::$machineInfo['datacenter'],self::$machineInfo['workid']);
            if (self::$redisResolverInstance == null) {
                try {
                    self::$redisResolverInstance = new RedisSequenceResolver();
                    self::$snowflakeInstance->setSequenceResolver(self::$redisResolverInstance);
                } catch (\Exception $e){
                }
            }
        }
        //每个表一个key，怕的就是key不够用，因为现在是1分钟用一个key zxiaofee
        self::$redisResolverInstance->setCachePrefix('{TRACKID:DATACENTER:' . self::$machineInfo['datacenter'] . ':WORKID:' . self::$machineInfo['workid'] .  ':TABLE:' . $table . '}');
        return self::$snowflakeInstance->id();
    }

    public static function getMachineInfo(){
        $machineInfo = [
            'datacenter' => 0,
            'workid' => 255,
        ];
        $path = '/data/kkaudio-api/machineinfo.json';
        if( file_exists($path)) {
            $body = file_get_contents($path);
            $body = json_decode($body,true);
            if (isset($body['datacenter'])) {
                $machineInfo['datacenter'] = $body['datacenter'];
            }

            if (isset($body['workid'])) {
                $result = explode('.', $body['workid']);
                $workid = $result[3]??0;
                $machineInfo['workid'] = $workid;
            }
        }
        return $machineInfo;
    }
}